package com.fighter.utils;

import com.fighter.mapper.FightOrderMapper;
import com.order.hit.crossover.platform.common.bean.Notice;
import com.order.hit.crossover.platform.common.bean.order.FightOrderState;
import com.order.hit.crossover.platform.common.dao.FightOrderDao;
import com.order.hit.crossover.platform.common.utils.PFResponse;
import com.order.hit.crossover.platform.common.utils.TimeChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Lei
 * @version 0.1
 * @date 2020/8/19
 */
@Component
public class OverTimeJudge {

    @Autowired
    private FightOrderMapper fightOrderMapper;


    /**
     * 判断拼单是否超时
     */
    public void judgeFightOrderIfOverTime(){
        List<FightOrderDao> list = this.fightOrderMapper.getAllFightOrder();

        for (FightOrderDao fightOrderDao : list){
            String end_time = fightOrderDao.getEnd_time();
            String nowTime = new SimpleDateFormat("yyyy.MM.dd.HH").format(new Date());
            if (TimeChange.getDate(end_time).before(TimeChange.getDate(nowTime)) && fightOrderDao.getFightOrderState().equalsIgnoreCase(FightOrderState.ORDER_DISPLAY.toString())){
                fightOrderDao.setFightOrderState(FightOrderState.ORDER_OVERTIME.toString());
                this.fightOrderMapper.updateOrder(fightOrderDao);

                //  生成通知
                String goodname = fightOrderDao.getGoodName();
                //  为订单发起顾客生成通知
                Notice from_notice = new Notice("您发起的关于" + goodname + "的拼单已超时",0,1,fightOrderDao.getUserId()+"");
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(from_notice, new HttpHeaders()), PFResponse.class);

                //  为参与拼单的顾客生成通知
                String[] pal = fightOrderDao.getParticipaters().split("\\.");
                for(String cs_id:pal) {
                    Notice to_notice = new Notice("您参与的关于" + goodname + "的拼单已超时",0,1,cs_id);
                    new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(to_notice, new HttpHeaders()), PFResponse.class);

                }
                //  为门店生成通知
                Notice store_notice = new Notice("您出售的关于商品" + goodname + "的拼单已超时",0,0,fightOrderDao.getStoreId());
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(store_notice, new HttpHeaders()), PFResponse.class);


            }
        }
    }
}
